package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.entity.User;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.UserMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.ErrorUtil;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * 登录功能校验
 *
 * @author 刘新明
 */
@Order(1)
@Service
public class Judge_1 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;
    @Autowired
    private UserMapper userMapper;
    @Value("${test.userId:1}")
    private String userId;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        //返回值对象创建
        StudentResult studentResult = new StudentResult();
        //设置题号
        studentResult.setItemNumber("1");
        //查询数据库中的用户信息
        User user = userMapper.getById(userId);
        String url = "http://" + ip + "/user/login";
        //封装请求参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("username", user.getUsername());
        params.add("password", user.getPassword());
        try {
            //发送请求，获取返回值
            String resultStr = httpUtil.doPostFormData(url, null, params);
            //设置studentResult对象的获取的返回值信息
            studentResult.setResult(resultStr);
            //返回值判断是否符合要求
            JsonResult jsonResult = JSONObject.parseObject(resultStr, JsonResult.class);
            if (jsonResult.getCode() == 200) {
                //符合要求，得分
                studentResult.setScore(2.0);
            }
        } catch (Exception e) {
            //捕获异常情况，如404访问报错，返回值解析异常等，设置异常日志信息
            studentResult.setResult(ErrorUtil.stackTraceToString(e));
        }
        //返回题号、获取到的返回值、分数
        return studentResult;
    }
}
